package com.jvmoutofmemory.platform.pushutil.dao;

import lombok.extern.slf4j.Slf4j;
import ognl.Ognl;
import ognl.OgnlException;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.ReflectionUtils;

import javax.persistence.Column;
import java.sql.ResultSet;
import java.sql.SQLException;

@Slf4j
public class DefaultRowMapper<T> implements RowMapper<T> {

        private Class<T> clazz;

        public DefaultRowMapper(Class<T> clazz) {
            this.clazz = clazz;
        }

        @Override
        public T mapRow(ResultSet rs, int rowNum) throws SQLException {
            log.info("mapping for class : {}", clazz);
            try {
                T instance = clazz.newInstance();

                ReflectionUtils.doWithFields(clazz, field -> {
                    Column column = AnnotationUtils.findAnnotation(field, Column.class);
                    if (column == null) {
                        return;
                    }

                    String name = column.name();
                    try {
                        Object value = rs.getObject(name);
                        if (value == null)
                            return;
                        Ognl.setValue(field.getName(), instance, value);
                    } catch (SQLException e) {
                        log.info("Error fetching value for column : {}", name);
                    } catch (OgnlException e) {
                        log.info("Error setting value for field : {}", field.getName());
                    }
                });

                return instance;
            } catch (Exception e) {
                log.warn("无法创建实例 ! {}", clazz);
                log.error(e.getMessage(), e);
                throw new RuntimeException("查询数据库转换对象失败!");
            }
        }
    }